class UsersController < ApplicationController
  before_filter :find_user, :only => [:show]
  before_filter :require_login, :only => [:edit, :update, :destroy]

  def index
    @users = User.scoped
    @users = @users.search(params[:search]) if params[:search].present?

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

  def show
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @user }
    end
  end

  def new
    @user = User.new
    @user.build_profile
    @user.build_settings

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
  end

  def edit
    @user = User.current
  end

  def create
    @user = User.new(params[:user])
    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render json: @user, status: :created, location: @user }
      else
        format.html { render action: "new" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @user = User.current
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @user.current.destroy
    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end

  private

  def find_user
    begin
      @user = User.where(username: params[:id]).first
      raise Mongoid::Errors::DocumentNotFound if @user.nil?
    rescue Mongoid::Errors::DocumentNotFound
      redirect_to users_path, alert: 'User not found.'
    end
  end
end